'use client';

import { WsStatus } from '@/app/earth/Map';

export class WebSocketService {
  private ws: WebSocket | null = null;
  private isConnected = false;
  
  constructor(
    private setStatus: (status: WsStatus) => void,
    private addLog: (message: any, type: 'client' | 'server') => void,
    private handleCommand: (response: any) => void,
    private url: string = 'ws://localhost:3000'
  ) {
    this.initWebSocket();
  }

  private initWebSocket() {
    this.ws = new WebSocket(this.url);
  
    this.ws.onopen = () => {
      this.isConnected = true;
      this.setStatus('connected');
      this.addLog({ type: 'system', message: 'WebSocket连接已建立' }, 'server');
    };
  
    this.ws.onmessage = (event) => {
      try {
        const response = JSON.parse(event.data);
        this.addLog(response, 'server');
        this.handleCommand(response);
      } catch (error) {
        this.addLog({ type: 'error', message: `解析错误: ${error}` }, 'server');
      }
    };
  
    this.ws.onerror = () => this.setStatus('error');
  
    this.ws.onclose = () => {
      this.isConnected = false;
      this.setStatus('disconnected');
    };
  }

  sendCommand(command: string, params: object) {
    if (this.isConnected && this.ws?.readyState === WebSocket.OPEN) {
      const message = { command, params };
      this.ws.send(JSON.stringify(message));
      this.addLog(message, 'client');
    } else {
      this.addLog(
        { type: 'error', message: `WebSocket未连接，无法发送命令 ${command}` },
        'client'
      );
    }
  }

  destroy() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}
